//
//  CJCommissionController.m
//  Boss
//
//  Created by admin on 2018/9/12.
//  Copyright © 2018年 admin. All rights reserved.
//

#import "CJCommissionController.h"
#import "CJCommissionView.h"
#import "CJCommissionRankCell.h"
#import "CJSeeBossController.h"
#import "CJCommissionHeader.h"
#import "CJCommissionModel.h"
#import "CJCommissionShareView.h"
#import "WXApi.h"
@interface CJCommissionController ()<UITableViewDelegate,UITableViewDataSource,CJCommissionViewDelegate,CJCommissionShareViewDelegate>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)CJCommissionView *commissionView;
@property (nonatomic,strong)CJCommissionHeader *headerModel;
@property (nonatomic,strong)NSMutableArray *listArray;
@property (nonatomic,strong)NSString *totalCount;
@property (nonatomic,strong)UIButton *shareStateBtn;
@property (nonatomic,strong)CJCommissionShareView *shareView;
@property (nonatomic,strong)NSString *shareType;

@end

@implementation CJCommissionController
-(NSMutableArray *)listArray
{
    if (!_listArray) {
        _listArray = [[NSMutableArray alloc]init];
    }
    return _listArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self loadCommission];
    [self loadShareList];
    
}
-(void)loadCommission
{
    WEAKSELF
    [WYHttpServer getCommissionWithBusinessId:self.businessId SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
       
        if (success) {
            weakSelf.headerModel = [CJCommissionHeader getCommissionModelFronJson:response[@"result"]];
            [weakSelf.tableView reloadData];
            
            [weakSelf changeBtn];
            
            
        }
        
        
        
    }];
}
-(void)changeBtn
{
    
    if (self.headerModel.state.integerValue==1) {
        
        [self.shareStateBtn setBackgroundColor:[UIColor hexStringToColor:@"#d8593f" alpha:1.0]];
        [self.shareStateBtn setTitleColor:[UIColor hexStringToColor:@"#ffffff" alpha:1.0] forState:UIControlStateNormal];
        
        
        if (self.headerModel.share.intValue) {
            [self.shareStateBtn setTitle:[NSString stringWithFormat:@"已获点击%@，即将赚¥%@",self.headerModel.totalClick,self.headerModel.profitAmount] forState:(UIControlStateNormal)];
             self.shareView.titleLabel.text = [NSString stringWithFormat:@"任何人通过您分享的内容成功阅读您将获得“转发佣金 %@ * 有效点击数”",self.headerModel.clickMoney];
            
            
            
        }else{
            [self.shareStateBtn setTitle:[NSString stringWithFormat:@"分享赚 %@ x 用户点击量",self.headerModel.clickMoney] forState:(UIControlStateNormal)];
        }
        self.shareStateBtn.userInteractionEnabled = YES;
    }else{
        [self.shareStateBtn setTitle:[NSString stringWithFormat:@"佣金已领完"] forState:(UIControlStateNormal)];
        [self.shareStateBtn setBackgroundColor:[UIColor hexStringToColor:@"#eaeaea" alpha:1.0]];
        [self.shareStateBtn setTitleColor:[UIColor hexStringToColor:@"#999999" alpha:1.0] forState:UIControlStateNormal];
        self.shareStateBtn.userInteractionEnabled = NO;
        
        
        
    }
    
    
    
    
    
    
}



-(void)loadShareUrl
{
    WEAKSELF
    [WYHttpServer getCommissionShareUrlWithBusinessId:self.businessId WithCommissionId:self.headerModel.commissionId SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            dispatch_async(dispatch_get_main_queue(), ^{
                // UI更新代码
                [self hideLoading];
                //self.showOffBtn.hidden = YES;
            });
            UIImageView *imageview = [[UIImageView alloc]init];
            
            [imageview sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@!default",response[@"result"][@"sharePicUrl"]]] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                
                if (self.shareType.integerValue==1) {
                     [weakSelf shareToWechateWithTitle:response[@"result"][@"businessName"] WithMessage:response[@"result"][@"message"] WithImage:image WithLink:response[@"result"][@"shareUrl"]];
                }else{
                    [weakSelf shareToFirendWithTitle:response[@"result"][@"businessName"] WithMessage:response[@"result"][@"message"] WithImage:image WithLink:response[@"result"][@"shareUrl"]];
                }
                
               
                
                
                
                
                
            }];
            
            
            
        }
        
        
        
        
    }];
}

-(void)shareToWechateWithTitle:(NSString *)title WithMessage:(NSString *)message WithImage:(UIImage *)image WithLink:(NSString *)link
{
    
    SendMessageToWXReq *req1 = [[SendMessageToWXReq alloc]init];
    
    // 是否是文档
    req1.bText =  NO;
    
    //    WXSceneSession  = 0,        /**< 聊天界面    */
    //    WXSceneTimeline = 1,        /**< 朋友圈      */
    //    WXSceneFavorite = 2,
    
    
    req1.scene = WXSceneSession;
    
    //创建分享内容对象
    WXMediaMessage *urlMessage = [WXMediaMessage message];
    urlMessage.title = title;//分享标题
    urlMessage.description = message;//分享描述
    [urlMessage setThumbImage:image];//分享图片,使用SDK的setThumbImage方法可压缩图片大小
    
    //创建多媒体对象
    WXWebpageObject *webObj = [WXWebpageObject object];
    webObj.webpageUrl = link;//分享链接
    
    //完成发送对象实例
    urlMessage.mediaObject = webObj;
    req1.message = urlMessage;
    
    //发送分享信息
    BOOL state =  [WXApi sendReq:req1];
    
    if (state) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isShare"];
    }
    
    
    
    
}
-(void)shareToFirendWithTitle:(NSString *)title WithMessage:(NSString *)message WithImage:(UIImage *)image WithLink:(NSString *)link
{
    SendMessageToWXReq *req1 = [[SendMessageToWXReq alloc]init];
    
    // 是否是文档
    req1.bText =  NO;
    
    //    WXSceneSession  = 0,        /**< 聊天界面    */
    //    WXSceneTimeline = 1,        /**< 朋友圈      */
    //    WXSceneFavorite = 2,
    
    
    req1.scene = WXSceneTimeline;
    
    //创建分享内容对象
    WXMediaMessage *urlMessage = [WXMediaMessage message];
    urlMessage.title = title;//分享标题
    urlMessage.description = message;//分享描述
    [urlMessage setThumbImage:image];//分享图片,使用SDK的setThumbImage方法可压缩图片大小
    
    //创建多媒体对象
    WXWebpageObject *webObj = [WXWebpageObject object];
    webObj.webpageUrl = link;//分享链接
    
    //完成发送对象实例
    urlMessage.mediaObject = webObj;
    req1.message = urlMessage;
    
    //发送分享信息
    BOOL state =  [WXApi sendReq:req1];
    
    if (state) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isShare"];
    }
    
    
    
    
    
}
-(void)loadShareList
{
    WEAKSELF
    [WYHttpServer getCommissionShareListWithBusinessId:self.businessId WithCurrenPage:@"1" SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            [weakSelf.listArray addObjectsFromArray:[CJCommissionModel getCommissionModelArrayFromJson:response[@"result"][@"detail"]]];
            weakSelf.totalCount =[ response[@"result"][@"totalCount"] stringValue];
            [weakSelf.tableView reloadData];
        }
    }];
}





-(void)setupUI
{
    self.navigationItem.title = @"转发领佣金";
    [self.view addSubview:self.tableView];
    self.tableView.estimatedSectionHeaderHeight = 270;
    self.tableView.rowHeight = 73;
    [self.tableView registerNib:[UINib nibWithNibName:@"CJCommissionRankCell" bundle:nil] forCellReuseIdentifier:@"CJCommissionRankCell"];
    
    UIButton *shareStateBtn  = [[UIButton alloc]init];
    [self.view addSubview:shareStateBtn];
    [shareStateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        if (kDevice_Is_iPhoneX) {
            make.bottom.mas_equalTo(-44);
        }else{
            make.bottom.mas_equalTo(0);
        }
        make.height.mas_equalTo(49);
    }];
    
    [shareStateBtn setBackgroundColor:[UIColor hexStringToColor:@"#d8593f" alpha:1.0]];
    [shareStateBtn setTitle:[NSString stringWithFormat:@"分享赚 0.00 x 用户点击量"] forState:UIControlStateNormal];
    [shareStateBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    shareStateBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    self.shareStateBtn = shareStateBtn;
    
    [shareStateBtn addTarget:self action:@selector(clickShareAction) forControlEvents:(UIControlEventTouchUpInside)];
    
}
-(void)clickShareAction
{
    UIButton *exitBtn = [[UIButton alloc]init];
    exitBtn.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    [exitBtn addTarget:self action:@selector(exitAction) forControlEvents:(UIControlEventTouchUpInside)];
    [self.maskView addSubview:exitBtn];
    
    [[UIApplication sharedApplication].keyWindow addSubview:self.maskView];
    [[UIApplication sharedApplication].keyWindow addSubview:self.shareView];
}

-(void)exitAction
{
    dispatch_async(dispatch_get_main_queue(), ^{
        // UI更新代码
        //self.showOffBtn.hidden = YES;
        [self.maskView removeFromSuperview];
        [self.shareView removeFromSuperview];
    });
 
    
}
-(void)clickWechate
{
    // [self setShareView:nil];
//    [self.maskView removeFromSuperview];
//    [self.shareView removeFromSuperview];
    dispatch_async(dispatch_get_main_queue(), ^{
        // UI更新代码
        //self.showOffBtn.hidden = YES;
        [self.maskView removeFromSuperview];
        [self.shareView removeFromSuperview];
    });
    self.shareType = @"1";
    [self showLoading:@""];
    [self loadShareUrl];
    
}
-(void)clickFriend
{
  //   [self setShareView:nil];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        // UI更新代码
        //self.showOffBtn.hidden = YES;
        [self.maskView removeFromSuperview];
        [self.shareView removeFromSuperview];
    });
    
//    [self.maskView removeFromSuperview];
//    [self.shareView removeFromSuperview];
//
    self.shareType = @"2";
    [self showLoading:@""];
    [self loadShareUrl];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.listArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CJCommissionRankCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CJCommissionRankCell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"CJCommissionRankCell" owner:nil options:nil].firstObject;
    }
    cell.rankLabel.text = [NSString stringWithFormat:@"%ld",indexPath.row+1];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    CJCommissionModel *model = self.listArray[indexPath.row];
    [cell setModel:model];
    
    
    return cell;
}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (self.headerModel) {
        [self.commissionView setHeaderModel:self.headerModel];
    }
    if (self.totalCount) {
        [self.commissionView setCountString:self.totalCount];
    }
    
    return self.commissionView;
}
-(void)clickMoreBoss
{
    CJSeeBossController *sbc = [[CJSeeBossController alloc]init];
    sbc.businessId = self.businessId;
    [self.navigationController pushViewController:sbc animated:YES];
}


-(CJCommissionView *)commissionView
{
    if (!_commissionView) {
        _commissionView = [[NSBundle mainBundle]loadNibNamed:@"CJCommissionView" owner:nil options:nil].firstObject;
        _commissionView.delegate = self;
    }
    
    
    return _commissionView;
}
- (UITableView *)tableView
{
    if (_tableView == nil) {
        CGRect frame = CGRectMake(0, self.navHeight, kScreenWidth, kScreenHeight-self.navHeight);
        _tableView = [[UITableView alloc] initWithFrame:frame
                                                  style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView setSeparatorStyle:(UITableViewCellSeparatorStyleNone)];
    }
    return _tableView;
}

-(CJCommissionShareView *)shareView
{
    if (!_shareView) {
        _shareView = [CJCommissionShareView sharedShareView];
        _shareView.frame = CGRectMake(0, kScreenHeight-140, kScreenWidth, 140);
        _shareView.delegate = self;
    }
    return _shareView;
    //return []
}



@end
